package unclassified.simple;


import java.util.Stack;

/**
 * 反转字符串中的单词 III
 * 示例：
 *
 * 输入："Let's take LeetCode contest"
 * 输出："s'teL ekat edoCteeL tsetnoc"
 *
 */
public class ReverseWordsinaStringIII_557 {

    public String reverseWords(String s) {
        //"Let's take LeetCode contest"
        //"s'teL ekat edoCteeL tsetnoc"
        String[] split = s.split(" ");
        StringBuilder sb = new StringBuilder();
        for (String s1 : split) {
            int i = 0, j = s1.length() - 1;
            char[] c = s1.toCharArray();
            while(i < j) {
                char temp = c[i];
                c[i] = c[j];
                c[j] = temp;
                i++;
                j--;
            }
            sb.append(String.valueOf(c)).append(" ");
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }

    //实验证明比数组交换还慢
    public String reverseWordsStack(String s) {
        Stack<Character> sc = new Stack<>();
        StringBuilder sb = new StringBuilder();
        String[] s1 = s.split(" ");
        for (String s2 : s1) {
            char[] chars = s2.toCharArray();
            for (char aChar : chars) {
                sc.push(aChar);
            }
            while(!sc.isEmpty()) {
                sb.append(sc.pop());
            }
            sb.append(" ");
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }


    public static void main(String[] args) {
        ReverseWordsinaStringIII_557 rw = new ReverseWordsinaStringIII_557();
        System.out.println(rw.reverseWords("Let's take LeetCode contest"));
    }
}
